package com.utils;

import com.TetrisServlet;
import org.apache.commons.lang.StringUtils;

import static com.utils.GlassPrinter.*;
import static org.junit.Assert.assertEquals;

/**
 * User: oleksandr.baglai
 * Date: 11/19/12
 * Time: 8:35 PM
 */
public class TetrisAssertions {

    private static final int GLASS_HEIGHT = 20;
    private static final int GLASS_WIDTH = 10;

    public static void assertAnswer(TetrisServlet servlet, String... params) {
        String expectedAnswer = params[0];
        String figure = params[1];
        String[] glass = new String[params.length - 2];
        System.arraycopy(params, 2, glass, 0, glass.length);

        String expectedGlassAfterDrop = makeGlass(glass);
        String expectedGlassBeforeDrop = expectedGlassAfterDrop.replaceAll("o", " ");

        String actualAnswer = servlet.answer(figure, 4, 18, expectedGlassBeforeDrop);
        String actualGlassAfterDrop = makeBetterPresent(getGlassWithDroppedFigure(actualAnswer, expectedGlassAfterDrop, figure));
        assertEquals(actualGlassAfterDrop, expectedAnswer, actualAnswer);

        assertFigureDropped(expectedAnswer, expectedGlassBeforeDrop, expectedGlassAfterDrop, figure);
    }

    private static void assertFigureDropped(String command, String glassBeforeDrop, String glassAfterDrop, String figure) {
        assertGlasses(glassAfterDrop, getGlassWithDroppedFigure(command, glassBeforeDrop, figure));
    }

    private static void assertGlasses(String expected, String actual) {
        assertEquals(makeBetterPresent(expected),
                makeBetterPresent(actual));
    }

    public static String makeGlass(String...lines) {
        String result = "";
        for (int index = lines.length - 1; index >= 0; index --) {
            result = result +
                    lines[index] +
                    StringUtils.repeat(" ", GLASS_WIDTH - lines[index].length());
        }
        final String EMPTY_LINE = StringUtils.repeat(" ", GLASS_WIDTH);
        result = result + StringUtils.repeat(EMPTY_LINE, GLASS_HEIGHT - lines.length);
        return result;
    }
}
